package com.study.lxpstudy.controller;

import com.study.lxpstudy.pojo.ResponseMessage;
import com.study.lxpstudy.pojo.User;
import com.study.lxpstudy.pojo.dto.UserDto;
import com.study.lxpstudy.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

@RestController // 接口方法返回对象，转换成json文博
@RequestMapping("/user") // localhost:8088/user
public class UserController {

    @Autowired
    IUserService userService;

    // 增加
    @PostMapping
    public ResponseMessage<User> add(@Validated @RequestBody UserDto user) {
        User newuser = userService.add(user);
        return ResponseMessage.success(newuser);
    }

//    public User createUser(@RequestBody User user) {
//        return user;
//    }

    @GetMapping("/list")
    public ResponseMessage<Iterable<User>> list() {
        Iterable<User> list = userService.list();
        return ResponseMessage.success(list);
    }

    // 查询
    @GetMapping("/{userId}")
    public ResponseMessage<User> get(@PathVariable Integer userId) {
        User userNew = userService.getUser(userId);
        return ResponseMessage.success(userNew);
    }

    // 删除
    @DeleteMapping("/{userId}")
    public ResponseMessage<String> delete(@PathVariable Integer userId) {
        userService.delete(userId);
        return ResponseMessage.success("success");
    }

    // 修改
    @PutMapping
    public ResponseMessage<User> put(@Validated @RequestBody UserDto user) {
        User newuser = userService.put(user);
        return ResponseMessage.success(newuser);
    }
}
